const app = getApp()
import { saveFile, saveOrUpdateSuggestion } from '../../../../../api/index'
const uploadOss = require('../../../../../utils/upload/uploadImg.js')
import { uuid } from '../../../../../utils/util'

Page({
  data: {
    form: {
      feedbackContext: '',
      fileList: []
    },
    fileList: []
  },
  async submit () {
    try {
      if (!this.data.form.feedbackContext) {
        wx.showToast({ title: '请输入反馈内容！', icon: 'none' })
        return
      }
      if (!this.data.form.fileList.length) {
        wx.showToast({ title: '请上传至少一张反馈图片！', icon: 'none' })
        return
      }
      let query = { ...this.data.form }
      let ids = query.fileList.map(item => { return item.fileId })
      query.fileIdList = ids
      await saveOrUpdateSuggestion({ ...query })
      wx.showToast({ title: '已收到您的反馈意见，正在核实中！', icon: 'none' })
      setTimeout(() => {
        wx.$nav.navigateBack()
      }, 1500)
      // wx.showToast({ title: '已收到您的反馈意见，正在核实中！', icon: 'none' })
      // wx.$nav.navigateBack()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  changeInput ({ currentTarget: { dataset: { key } }, detail: { value } }) {
    this.setData({ ['form.' + key]: value })
  },
  deleteTempFile ({ currentTarget: { dataset: { index } } }) {
    this.data.fileList.splice(index, 1)
    this.setData({ fileList: this.data.fileList })
  },
  deleteFile ({ currentTarget: { dataset: { index } } }) {
    this.data.form.fileList.splice(index, 1)
    this.setData({ 'form.fileList': this.data.form.fileList })
  },
  async againUpload ({ target: { dataset: { key, item, index } } }) {
    let _this = this
    let tempFiles = this.data[key]
    tempFiles[index].success = ''
    _this.setData({
      [key]: tempFiles
    })
    const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
    if (file) {
      const { ResultSet } = await saveFile({
        fileList: [{
          fileSize: item.size,
          fileName: file.fileName,
          fileUrl: file.fileUrl
        }]
      })
      tempFiles.splice(index, 1)
      _this.data.form[key][index] = {
        uuid: item.uuid,
        fileId: ResultSet.userData.fileIdList[0].fileId,
        fileName: file.fileName,
        fileUrl: ResultSet.userData.fileIdList[0].url,
        url: ResultSet.userData.fileIdList[0].fileUrl
      }
    } else {
      tempFiles[index].success = 1
      _this.setData({
        [key]: tempFiles
      })
    }
    _this.setData({
      [key]: tempFiles,
      ['form.' + key]:  _this.data.currentDiyItem[key]
    })
  },
  addFile ({ target: { dataset: { key, num } } }) {
    let _this = this
    if (parseInt(num) - this.data.form[key].length === 0) {
      wx.showToast({ title: `最多只能上传${num}图片！`, icon: 'none' })
      return
    }
    wx.chooseMedia({
      count: parseInt(num),
      mediaType: ['image'],
      async success (res) {
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data[`${key}`].push(...res.tempFiles)
        _this.setData({
          [`${key}`]: _this.data[`${key}`]
        })
        let tempFiles = _this.data[`${key}`]
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
            if (file) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileName: file.fileName,
                  fileUrl: file.fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileName: file.fileName,
                fileUrl: ResultSet.userData.fileIdList[0].url,
                url: ResultSet.userData.fileIdList[0].fileUrl
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                [`${key}`]: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.form[key].push(...tempFileList)
        _this.data.form[key].forEach((item) => {
          let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        })
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key]
        })
      }
    })
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
})